package com.cloud.controller;

import com.cloud.util.FileUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/images")
public class ImageController {

    @Resource
    private HttpServletResponse response;

    private static String IMAGE_DIR = "input_graph/avatar/";

    static {
        if (!FileUtil.isMac()) {
            IMAGE_DIR = "/data/" + IMAGE_DIR;
        } else {
            IMAGE_DIR = "/Users/fuhaixu/Desktop/work/program_journey/cloud_computing/github_data_analysis/cloud_backend/" + IMAGE_DIR;
        }
    }

    @GetMapping(value = "/{imgName}")
    public void getImage(@PathVariable String imgName) throws IOException {
        OutputStream os = null;
        try {
            File imgFile = new File(IMAGE_DIR + imgName);
            if (!imgFile.exists()) imgFile = new File(IMAGE_DIR + "404.jpg");
            BufferedImage image = ImageIO.read(new FileInputStream(imgFile));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (IOException e) {

        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }
}
